package com.example.job_backend.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 * 因为不属于controller层，也不属于service层，所以用component注解来存放到IOC容器里
 */
@Component
public class AliOSSUtils {
    private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    private String bucketName = "jobsystem";
    private String accessKeyId = "LTAI5tGS91r6gx3b1hWwakPC";
    private String accessKeySecret = "Vn2uyf2jPbmjcOJlTpTzpaj4Z975T7";

    /**
     * 实现上传文件到OSS
     */
    public String uploadFile(MultipartFile file) throws IOException {
        //获取文件的输入流
        InputStream inputStream = file.getInputStream();

        //避免文件名重复导致文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;

        ossClient.shutdown();
        return url;
    }

    // 新增方法：上传本地文件到OSS
    public String uploadLocalFile(File file) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 生成唯一文件名
        String fileName = UUID.randomUUID() + ".docx";

        try (InputStream inputStream = new FileInputStream(file)) {
            ossClient.putObject(bucketName, fileName, inputStream);
        } finally {
            ossClient.shutdown();
        }

        return "https://" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
    }

    /**
     * 根据OSS文件URL下载到临时文件
     */
    public File downloadByUrl(String ossUrl) throws IOException {
        // 解析出Bucket和ObjectKey
        String[] parts = parseOssUrl(ossUrl);
        String bucket = parts[0];
        String objectKey = parts[1];

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        File tempFile = File.createTempFile("template_", ".docx");

        try (OSSObject ossObject = ossClient.getObject(bucket, objectKey);
             InputStream inputStream = ossObject.getObjectContent();
             FileOutputStream outputStream = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } finally {
            ossClient.shutdown();
        }

        return tempFile;
    }

    /**
     * 解析OSS URL格式：https://{bucket}.{endpoint}/{key}
     */
    private String[] parseOssUrl(String url) {
        String cleanUrl = url.replace("https://", "");
        int firstSlash = cleanUrl.indexOf('/');
        String bucketPart = cleanUrl.substring(0, firstSlash);
        String key = cleanUrl.substring(firstSlash + 1);

        return new String[]{
                bucketPart.split("\\.")[0], // 提取bucket名称
                key
        };
    }

}
